﻿using System;
using System.Windows.Threading;
using Ags.MonsterTools.Common;
using Microsoft.Practices.Prism.Regions;
using System.Linq;
using System.Windows.Controls;

namespace Ags.MonsterTools
{
    public class StatusbarServiceImpl : IStatusbarService, IDisposable
    {
        private const int TimerInterval = 5;
        private IRegionManager _rm;
        private Label _uc;
        private DispatcherTimer _timer;

        public StatusbarServiceImpl(IRegionManager rm)
        {
            _rm = rm;
        }

        public void WriteMessage(string msg)
        {
            WriteMessageCore(msg);
        }

        private void WriteMessageCore(string msg)
        {
            SetupTimer();   
            if (!_rm.Regions[RegionConstants.STATUSBARREGION].Views.Any())
            {

                _uc = new Label() { Content = msg };
                _rm.RegisterViewWithRegion(RegionConstants.STATUSBARREGION, () => _uc);
            }
            else
            {
                _uc.Content = msg;
            }
            StartTimer();
        }

        private void StartTimer()
        {
            if (!_timer.IsEnabled)
                _timer.Start();
        }

        private void SetupTimer()
        {
            if (_timer == null)
            {
                _timer = new DispatcherTimer {Interval = new TimeSpan(0, 0, TimerInterval)};
                _timer.Tick += _timer_Tick;
            }
        }

        void _timer_Tick(object sender, EventArgs e)
        {
            _timer.Stop();
            _uc.Content = string.Empty;
        }

        public void Dispose()
        {
            _timer = null;
            _uc = null;
            _rm = null;
        }
    }
}
